//
//  CityViewController.m
//  dangdang
//
//  Created by air on 16/3/4.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "CityViewController.h"
#import "CityFirstTableViewCell.h"
#import "CitySecondTableViewCell.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "CityNameObject.h"

@interface CityViewController ()

{
    AMapLocationManager * _mapLocationManager;
}

@property (nonatomic, strong) NSDictionary * dic;
@property (nonatomic, strong) NSArray * keyArray;
@property (nonatomic, strong) NSMutableArray * cityArray;
@property (nonatomic) BOOL isExist;
@property (nonatomic, strong) NSArray * orderCountArray;
@property (nonatomic, strong) NSMutableArray * orderDetailsArray;

@end

@implementation CityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initialization];
    
    [self connection];
    
    [self judge];
    
    [self updateUI];
    
    self.title = @"切换位置";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initialization{
    _orderDetailsArray = [NSMutableArray new];
    
    _isExist = YES;
    _cityArray = [NSMutableArray new];
    
    _dic = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"citydict" ofType:@"plist"]];
    
    _keyArray = [_dic.allKeys sortedArrayUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:nil ascending:YES], nil]];
}

- (void)connection{
    NSString * token = userObject.accessToken;
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
        
    [self postRequestWithMethodName:@"common/get_city_list" andParams:params andSender:nil];
}

- (void)judge{
    NSString * plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"cityList.plist"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath] == NO){
        _isExist = NO;
    }
}

- (void)updateUI{
    UIBarButtonItem *barBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"hk_detete.png"] style:UIBarButtonItemStylePlain target:self action:@selector(returnView)];
    self.navigationItem.leftBarButtonItem = barBtn;
    
    _cityTableView.rowHeight = UITableViewAutomaticDimension;
    _cityTableView.estimatedRowHeight = 44.0;
}

- (void)returnView{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)locationButton:(UIButton *)sender {
    _mapLocationManager = [[AMapLocationManager alloc] init];
    
    [_mapLocationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    [_mapLocationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                
            if (error.code == AMapLocationErrorLocateFailed)
            {
                    return;
            }
        }
            
        if (regeocode)
        {
            cityObject.city = regeocode.city;
            cityObject.sucessCity = @"city";
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

#pragma mark UITableViewDataSource && Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_isExist) {
        return 2;
    }else{
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_isExist) {
        if (section == 0) {
            return 1;
        }else{
            return _orderDetailsArray.count;
        }
    }else{
        return _orderDetailsArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell *cell = nil;
    
    if (_isExist) {
        if (indexPath.section == 0) {
            CityFirstTableViewCell * firstCell = [tableView dequeueReusableCellWithIdentifier:@"cityFirstTableViewCell"];
            
            for (UIButton * button in firstCell.buttonArray) {
                button.layer.borderWidth = 1;
                button.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] CGColor];
                button.layer.cornerRadius = 8;
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button addTarget:self action:@selector(returnView:) forControlEvents:UIControlEventTouchUpInside];
            }
            
             NSString * plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"cityList.plist"];
            _cityArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
            if (_cityArray.count == 1) {
                [firstCell.firstButton setTitle:_cityArray[0] forState:UIControlStateNormal];
                firstCell.secondButton.hidden = YES;
                firstCell.thirdButton.hidden = YES;
            }else if (_cityArray.count == 2){
                [firstCell.firstButton setTitle:_cityArray[0] forState:UIControlStateNormal];
                [firstCell.secondButton setTitle:_cityArray[1] forState:UIControlStateNormal];
                firstCell.thirdButton.hidden = YES;
            }else{
                [firstCell.firstButton setTitle:_cityArray[0] forState:UIControlStateNormal];
                [firstCell.secondButton setTitle:_cityArray[1] forState:UIControlStateNormal];
                [firstCell.thirdButton setTitle:_cityArray[2] forState:UIControlStateNormal];
            }
            
            cell = firstCell;
        }else{
            CitySecondTableViewCell * secondCell = [tableView dequeueReusableCellWithIdentifier:@"citySecondTableViewCell"];
            
            CityNameObject * orderObject = [[CityNameObject alloc] init];
            orderObject = _orderDetailsArray[indexPath.row];
            secondCell.cityLabel.text = orderObject.cityName;
            
            cell = secondCell;
        }
    }else{
        CitySecondTableViewCell * secondCell = [tableView dequeueReusableCellWithIdentifier:@"citySecondTableViewCell"];
        
        CityNameObject * orderObject = [[CityNameObject alloc] init];
        orderObject = _orderDetailsArray[indexPath.row];
        secondCell.cityLabel.text = orderObject.cityName;
        
        cell = secondCell;
    }
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (_isExist) {
        if (section == 0) {
            return @"常用城市";
        }
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * plistPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"cityList.plist"];
    CityNameObject * object = [[CityNameObject alloc] init];
    object = _orderDetailsArray[indexPath.row];
    cityObject.cityID = object.cityID;
    if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath] == NO){
        NSMutableArray * cityDataArray = [[NSMutableArray alloc]init];
        [cityDataArray addObject:object.cityName];
        [cityDataArray writeToFile:plistPath atomically:YES];
        cityObject.city = object.cityName;
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        if (indexPath.section == 1) {
            _cityArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
            for (NSString * string in _cityArray) {
                if ([object.cityName isEqualToString:string]){
                    cityObject.city = object.cityName;
                    [self.navigationController popViewControllerAnimated:YES];
                    return;
                }
            }
            if (_cityArray.count < 3) {
                [_cityArray addObject:object.cityName];
                [_cityArray writeToFile:plistPath atomically:YES];
                cityObject.city = object.cityName;
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [_cityArray removeLastObject];
                [_cityArray addObject:object.cityName];
                [_cityArray exchangeObjectAtIndex:2 withObjectAtIndex:0];
                [_cityArray exchangeObjectAtIndex:1 withObjectAtIndex:2];
                [_cityArray writeToFile:plistPath atomically:YES];
                cityObject.city = object.cityName;
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
        
}

- (void)returnView:(UIButton *)button{
    CityNameObject * object = [[CityNameObject alloc] init];
    for (int i = 0; i < _orderDetailsArray.count; i ++) {
        object = _orderDetailsArray[i];
        if ([button.titleLabel.text isEqualToString:object.cityName]) {
            cityObject.cityID = object.cityID;
            break;
        }
    }
    cityObject.city = button.titleLabel.text;
    [self.navigationController popViewControllerAnimated:YES];
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([code isEqualToString:@"0"] && [urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"common/get_city_list"]]){
            _orderCountArray = [result objectForKey:@"retmsg"];
            for (int i = 0; i < _orderCountArray.count; i ++) {
                CityNameObject * orderObject = [[CityNameObject alloc] init];
                _dic = _orderCountArray[i];
                orderObject.cityName = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"city_name"]];
                orderObject.cityID = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"id"]];
                
                [_orderDetailsArray addObject:orderObject];
                [_cityTableView reloadData];
            }
        }
    }
}

@end
